//
//  KLCurrencyPickerController.m
//  KLCurrency
//
//  Created by apple on 2017/12/4.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLCurrencyPickerController.h"

#import "KLCurrencyEntity.h"
#import "KLCurrencyGroup.h"
#import "KLCurrencyService.h"
#import "KLCurrencyHelper.h"
#import "KLPlistHelper.h"

#import "KLCurrencyPickerCell.h"

#import "KLCurrencyPickerSearchResultController.h"

static const CGFloat tableViewCellHeight = 49.0f;
static const CGFloat headerSectionHeight = 30.0f;

@interface KLCurrencyPickerController ()<UITableViewDataSource, UITableViewDelegate, KLCurrencyPickerSearchResultControllerDelegate>
@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, strong) KLCurrencyPickerSearchResultController *searchResultsController;

@property (strong, nonatomic) NSArray<KLCurrencyGroup *> *currencyGroupArray;//所有分组货币
@property (strong, nonatomic) NSArray<KLCurrencyEntity *> *commonCurrencyArray;//常用货币
@property (strong, nonatomic) NSArray<NSString *> *sectionIndexTitles;//货币列表分组标题
@end

@implementation KLCurrencyPickerController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //从数据库中取出所有数据
    [self getAllData];
    //设置UI
    [self setupUI];
}

- (void)setupUI {
    //导航栏
    [self initNavigationItem];
    //列表
    [self initTableView];
}

- (void)initNavigationItem {
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
    [leftItem setTintColor:UIColorFromRGB(0X99A4BF)];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"切换货币";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18.0],
       NSForegroundColorAttributeName:[UIColor blackColor]}];
    
    //搜索货币功能 searchCurrencyWithPinyinOrAbbreviation)
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchCurrency)];
    self.navigationItem.rightBarButtonItem.tintColor = UIColorFromRGB(0x99A4BF);
}

- (void)popBack {
    if (self.delegate && [self.delegate respondsToSelector:@selector(chosenCurrency:)]) {
        [self.delegate chosenCurrency:nil];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchCurrency {
    KLCurrencyPickerSearchResultController *filter = [[KLCurrencyPickerSearchResultController alloc] init];
    filter.delegate = self;
    filter.changeCurrencyEntity = self.changeCurrencyEntity;
    [self presentViewController:filter animated:YES completion:nil];
}

- (void)getAllData {

    self.currencyGroupArray = [KLCurrencyService getAllCurrencyGroups];
    self.commonCurrencyArray = [KLCurrencyService getCommonCurrencyEntities];

    NSMutableArray *tempNameArr = [[KLCurrencyHelper getAllCurrencyGroupNames] mutableCopy];
    [tempNameArr insertObject:@"#" atIndex:0];
    self.sectionIndexTitles = [tempNameArr mutableCopy];
}

- (void)initTableView {
    CGFloat tableViewY = kNavigationBarHeight + kStatusBarHeight;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableViewY, kScreenWidth, kScreenHeight - tableViewY) style:UITableViewStylePlain];
    tableView.bounces = NO;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = tableViewCellHeight;
    tableView.sectionHeaderHeight = headerSectionHeight;
    tableView.sectionFooterHeight = CGFLOAT_MIN;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.tableFooterView = [UIView new];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    //注册cell
    [tableView registerNib:[UINib nibWithNibName:@"KLCurrencyPickerCell" bundle:nil] forCellReuseIdentifier:@"picker"];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.currencyGroupArray.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.commonCurrencyArray.count;
    } else {
        KLCurrencyGroup *group = self.currencyGroupArray[section-1];
        NSArray *currencies = group.currencies;
        return currencies.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        KLCurrencyEntity *currency = self.commonCurrencyArray[indexPath.row];
        KLCurrencyPickerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picker"];
        if ([currency.abbreviation isEqualToString:self.changeCurrencyEntity.abbreviation]) {
            currency.changing = YES;
        } else {
            currency.changing = NO;
        }
        cell.currencyEntity = currency;
        return cell;
    } else {
        KLCurrencyGroup *group = self.currencyGroupArray[indexPath.section-1];
        NSArray *currencies = group.currencies;
        KLCurrencyEntity *currency = currencies[indexPath.row];
        KLCurrencyPickerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"picker"];
        if ([currency.abbreviation isEqualToString:self.changeCurrencyEntity.abbreviation]) {
            currency.changing = YES;
        } else {
            currency.changing = NO;
        }
        cell.currencyEntity = currency;
        return cell;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"常用货币";
    } else {
        KLCurrencyGroup *group = self.currencyGroupArray[section-1];
        NSString *sectionHeader = group.group;
        return sectionHeader;
    }
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return tableViewCellHeight;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
//    return headerSectionHeight;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return CGFLOAT_MIN;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        //取出选中模型
        KLCurrencyEntity *currency = self.commonCurrencyArray[indexPath.row];
        [self currencyDidSelected:currency];
    } else {
        //取出选中模型
        KLCurrencyGroup *group = self.currencyGroupArray[indexPath.section-1];
        NSArray *currencies = group.currencies;
        KLCurrencyEntity *currency = currencies[indexPath.row];
        [self currencyDidSelected:currency];
    }
}

- (void)currencyDidSelected: (KLCurrencyEntity *)currency {
    if (self.delegate && [self.delegate respondsToSelector:@selector(chosenCurrency:)]) {
        NSArray *mainArr = [KLCurrencyService getMainCurrencies];
        if ([mainArr containsObject:currency.abbreviation]) {
            //选中的是当前主界面货币，不做任何处理，直接返回
            [self.delegate chosenCurrency:nil];
        } else {
            //选中的是非当前主界面货币，进行数据库缓存
            //改写数据库主界面货币和常用货币
            [KLCurrencyService convertOldMainCurrency:self.changeCurrencyEntity toNewMainCurrency:currency completion:^{
                //改写主界面主货币队列名称
                NSMutableArray *tempMain = [[KLCurrencyService getMainCurrencies] mutableCopy];
                [tempMain replaceObjectAtIndex:self.changingIndex withObject:currency.abbreviation];
                NSArray *newMainArr = [tempMain mutableCopy];
                //plist存储主界面货币
                [KLCurrencyService saveMainCurrencies:newMainArr completion:^{
                    //主界面修改缓存模型
                    [self.delegate chosenCurrency:currency];
                } failure:^(NSString *error) {
                    
                }];
            } failure:^(NSString *error) {
                
            }];
        }
        //回到主界面
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - common delete 支持非选择常用货币删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        KLCurrencyEntity *cur = [self.commonCurrencyArray objectAtIndex:indexPath.row];
        if (cur.main == NO) {
            return YES;
        }
    }
    return NO;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        KLCurrencyEntity *cur = [self.commonCurrencyArray objectAtIndex:indexPath.row];
        if (cur.main == NO) {
            return @"删除";
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        KLCurrencyEntity *cur = [self.commonCurrencyArray objectAtIndex:indexPath.row];
        if (cur.main == NO) {
            //数据库删除
            [KLCurrencyService deleteCommonCurrency:cur completion:^{
                //数据源删除
                NSMutableArray *tempCommon = [self.commonCurrencyArray mutableCopy];
                [tempCommon removeObjectAtIndex:indexPath.row];
                self.commonCurrencyArray = [tempCommon mutableCopy];
                //视图删除
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            } failure:^(NSString *error) {
                
            }];
        }
    }
}

/**
 *设置右侧导航栏引索
 */
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    //KVC
    return self.sectionIndexTitles;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - search result
- (void)chosenFilteredCurrency:(KLCurrencyEntity *)currency {
    [self currencyDidSelected:currency];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
